package br.Servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import br.Controller.AgenciaController;

/**
 * Servlet implementation class CadAgenciaServlet
 */
@WebServlet("/CadAgenciaServlet")
public class CadAgenciaServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public CadAgenciaServlet() {
		super();

	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		System.out.println("get");
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		System.out.println("post");
		PrintWriter out = response.getWriter();
		try {
			doInser(request, response);
		} catch (Exception e) {
			out.println("ocorreu algum erro");
			e.printStackTrace();
		}

	}

	protected void doInser(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		PrintWriter out = response.getWriter();

		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		int agencia = Integer.parseInt(request.getParameter("agencia"));
		String nome = request.getParameter("nome");

		Connection conn = null;

		try {

			conn = new br.Connection.ConnectionFactory().getConnection();
			AgenciaController.inserir(conn, agencia, nome);

			out.print("<script type=\"text/javascript\">	alert(\"Cadastrado com sucesso.\");</script>");
			out.print("<meta http-equiv='refresh' content='0;url=/bancodados2/Index.jsp'>");
			conn.commit();

		} catch (Exception e) {
			e.printStackTrace();
			try {
				conn.rollback();
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		} finally {
			try {
				conn.close();
			} catch (Exception ex) {
			}
		}
	}
}
